package com.javacv4axe.core;

import org.axe.extra.timer.TimerTask;

/**
 * 异步的帧处理器
 * 缓存的frame非线程同步
 */
public abstract class AsynchronousFrameHandler extends TimerTask{
	
	private int cacheFrameFps;//每秒多少帧画面被捕获
	private long lastCacheFrameTime = 0;
	
	private int handleFps;//没秒处理多少帧画面
	private long lastHandleTime = 0;
	
	private CammeraWatcher cammeraWatcher = null;
	private FramePack framePackCache = null;
	
	/**
	 * 将一帧缓存起来
	 */
	public void cacheFrame(final FramePack framePack){
		framePackCache = framePack;
		countCacheFrameFps();
	}
	
	public void countCacheFrameFps(){
		if(debug()){
			long now = System.currentTimeMillis();
			cacheFrameFps = (int)(1000/(now-lastCacheFrameTime));
			lastCacheFrameTime = now;
		}
	}
	
	@Override
	public final void doSomething() {
		if(framePackCache != null){
//			LogUtil.log(name()+" 处理frameCache:"+frameCache);
			handle(framePackCache);
			framePackCache = null;//线程安全不安全无所谓，因为最终只要frameCache=null，就会停止检测
			if(debug()){
				long now = System.currentTimeMillis();
				handleFps = (int)(1000/(now-lastHandleTime));
				lastHandleTime = now;
			}
		}
	}
	
	public void setCammeraWatcher(CammeraWatcher cammeraWatcher) {
		this.cammeraWatcher = cammeraWatcher;
	}
	
	public CammeraWatcher getCammeraWatcher() {
		return cammeraWatcher;
	}
	
	/**
	 * 交给实现类处理
	 * 处理类可以返回boolean来说明处理结果
	 */
	public abstract boolean handle(FramePack framePackCache);
	
	public boolean debug(){
		return false;
	};
	
	@Override
	public double timeSec() {
		return 1;//TimerTask最高速度1秒10次
	}
	
	@Override
	public final boolean doOnceAfterStartup() {
		return false;//默认启动时不执行
	}
	
	public int getCacheFrameFps() {
		return cacheFrameFps;
	}
	
	public int getHandleFps() {
		return handleFps;
	}
}
